import React, { Component } from 'react';
import moment from 'moment';  //time格式工厂
import style from './Organization.less';
import { connect } from 'dva';
import { FormattedMessage, formatMessage } from 'umi/locale'; //此方法引入的数据可以在src/locales中配置
import PageHeaderWrapper from '@/components/PageHeaderWrapper';  //头部的那个版块的东西
import ModalBoxForm from './ModalBox';
import DetailsModel from './DetailsModel';
import {
  Button,
  Input,
  DatePicker,
  Form,
  Row,
  Col,
  Table,
  Modal,
  Select,
  Card,
  PageHeader,
  Alert,
  Pagination,
  message,
  Icon,
  Tree,
  Empty,
} from 'antd';


//表单
const FormItem = Form.Item;

//所属租户选择框
const Option = Select.Option;

//多级选择树
const TreeNode = Tree.TreeNode;



//页头&&面包屑
const routes = [
  {
    path: 'index',
    breadcrumbName: 'First-level Menu',
  },
  {
    path: 'first',
    breadcrumbName: 'Second-level Menu',
  },
  {
    path: 'second',
    breadcrumbName: 'Third-level Menu',
  },
];



//命名空间
const namespace = 'Organization';

const mapStateToProps = function(state) {
  const dataSource = state[namespace].dataSource;

  return {
    dataSource: dataSource,   //全部数据
    dataList: dataSource ? dataSource.data.list:[],   //专门给表格使用的
    total_elements: dataSource?dataSource.total_elements: 0
    // dataList: []
  }

};

const mapDispatchToProps = function(dispatch) {
  return {
    dispatch: dispatch
  };
};


@connect(mapStateToProps, mapDispatchToProps)
@Form.create()
class Organization extends Component {

  componentDidMount() {

    const { dispatch } = this.props;

    //查询“所属租户”功能的选项
    dispatch({
      type: `${namespace}/findAll`,
      callback: (res) => {
        this.setState({
          tenantTreeData: res.data,
        })
        if (res && res.data && res.data.length === 1){
          const fatherProps= {
            title:res.data[0].tenant_name,
            key: res.data[0].tenant_id,
          }
          this.setState({
            fatherProps: fatherProps
          });
          dispatch({
            type: `${namespace}/deptsTree`,
            payload: {
              tenant_id: res.data[0].tenant_id
            },
            callback: (r) => {
              this.setState({
                treeOne: r && r.data ? r.data : [],
              });
            },
          });

        }
      }
    })

  }

  state = {
    //分页相关状态
    page_size: 10,
    page_num: 1,
    //模态框相关状态
    loading: false,
    visible: false,
    //编辑内容状态
    nowRow: null,
    //编辑标识符,父级子级标识符
    modalFlag: '',
    //详情模态框
    datailsState: false,
    //当前选中的树的值
    selectedKeys: '',
    selectedKeys_key: null,
    nowNode: null,
    //租户选项
    tenantTreeData: null,
    nowTenant: '尚未选择',
    //组织机构树data
    deptsTree: null,
    //当前租户
    fatherProps: null,
    //请求到的当前节点组织机构信息
    nowData: null,
    //两个按钮状态
    addBrother: true,
    treeOne:[],
    editInfo: true,
    autoExpandParent: true,


  };


  //查看详情
  detailsList() {
    if(this.state.selectedKeys_key == null){
      message.error('必须选择一个左侧节点才能查看详情');
      return false;
    }
    if(this.state.selectedKeys_key == 'father'){
      message.error(`${this.state.selectedKeys}是${formatMessage({ id: 'iot.organization.organization_search.tenant_name'})}，没有${formatMessage({ id: 'iot.organization.dept_nickname'})}信息`);
      return false;
    }
    this.props.dispatch({
      type: `${namespace}/detailsSearch`,
      payload: this.state.selectedKeys_key,
      callback: (res) => {
        this.setState({
          nowData: res
        })
      }
    });
    this.setState({
      datailsState: true,
    })

  }

  //子模态框组件修改state保持模态框关闭方法
  childModalChangeModalState () {
    this.setState({
      visible: false,
    });
  }

  //关闭-模态框
  handleCancel = () => {
    this.setState({ visible: false });
  };

  //显示-模态框
  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  //关闭详情模态框
  closeDatails = () => {
    this.setState({
      datailsState: false,
      nowRow: null,
    })
  }

  //删除处理（预留的）
  deleteList(){
    if(this.state.selectedKeys_key == null){
      message.error('必须选择一个左侧节点才能删除');
      return false;
    }
    if(this.state.selectedKeys_key == 'father'){
      message.error('不能删除租户节点!');
      return false;
    }
    const props = this.props;
    const _this = this;
    const tenant_id = this.state.fatherProps.key;
    const dept_id = this.state.selectedKeys_key;
    Modal.confirm({
      title: '确认删除吗',
      content: '您确定要删除这个'+formatMessage({ id: 'iot.organization.dept_nickname'})+'吗？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        //发送删除请求
        props.dispatch({
          type: `${namespace}/deleteBegin`,
          payload: {
            tenant_id: tenant_id,
            dept_id: dept_id,
          },
          callback: (res) =>{

            if(res.return_code === "SUCCESS"){
              message.success('删除成功');
              //清空当前节点
              _this.setState({
                selectedKeys: '',
                selectedKeys_key: null,
              })
                //代入当前租户状态重新查询一次树
                props.dispatch({
                  type: `${namespace}/deptsTree`,
                  payload: {
                    tenant_id: tenant_id
                  },
                  callback: (res) => {
                    _this.setState({
                      deptsTree: res.data,
                      treeOne: res.data,
                    })
                  }
                });
            }
          }
        });

      },
      onCancel() {
        return false;
      },
    })

  }

  //设置标识符为新建标识符并且显示模态框 （预留修改组织机构功能 20190322尚未有）
  changeFlag = (flag) => {
    if(this.state.selectedKeys_key == null){
      message.error('必须选择一个左侧节点才能继续操作！');
      return false;
    }
    if(this.state.selectedKeys_key == 'father' && flag == 'brother'){
      message.error('这个节点不能增加同级节点！');
      return false;
    }
    if(this.state.selectedKeys_key == 'father' && flag == 'edit'){
      message.error('这个节点不能编辑！');
      return false;
    }
    this.setState({
      visible: true,
      modalFlag: flag,
    });

  }

  //所属组织机构树渲染
  renderTreeNodes = data => data.map((item) => {
    if (item.depts) {
      return (
        <TreeNode title={item.dept_name} key={item.dept_id} dataRef={item} value={item.dept_id}>
          {this.renderTreeNodes(item.depts)}
        </TreeNode>
      );
    }else{
      return (
        <TreeNode title={item.dept_name} key={item.dept_id} dataRef={item} value={item.dept_id}>
        </TreeNode>
      );
    }
  })

  //选中树时的方法
  treeNow = (selectedKeys,e) => {
    if(e.node.props.pos === '0-0'){
      this.setState({
        selectedKeys: e.node.props.title,
        selectedKeys_key: 'father',
      })
    }else{
      this.setState({
        selectedKeys: e.node.props.title,
        selectedKeys_key: e.node.props.dataRef.dept_id,
        nowNode: e.node.props,
      })
    }
  }

  //查询表单的回调方法
  setTreeMothed = (res) => {
    this.setState({
      deptsTree: res,
      treeOne: res
    })
  }

  //修改的回调方法
  clearMothed = (res) => {
    this.setState({
      deptsTree: res,
      treeOne: res,
      selectedKeys: '',
      selectedKeys_key: null,

    })
  }

  //当点击搜索时，组织机构树父元素的title和key
  fatherMethod = (res) => {
    this.setState({
      fatherProps: res
    })

  }

  render() {

    //树级数据
    const treeData = this.state.deptsTree?this.state.deptsTree:"";
    const treeOne = this.state.treeOne? this.state.treeOne:"";
    //树里有时终须有，树里无时莫强求
    let treeShow = (
      <div>
        <p className={style.p1}>{formatMessage({ id: 'iot.organization.dept_nickname'})}如下：</p>
        <Tree className={style['input-box']} treeCheckable="true" showLine={true} onSelect={this.treeNow} autoExpandParent={this.state.autoExpandParent}>
          <TreeNode title={this.state.fatherProps?this.state.fatherProps.title:'父节点'} key={this.state.fatherProps?this.state.fatherProps.key:'happy'}>
            {this.renderTreeNodes(treeOne !== "" ? treeOne : treeData)}
          </TreeNode>
        </Tree>
      </div>
    );
    if(this.state.fatherProps == null || this.state.fatherProps.length == 0){
      treeShow = <Empty>必须先搜索一个{formatMessage({ id: 'iot.organization.organization_search.tenant_name'})}才能查看{formatMessage({ id: 'iot.organization.dept_nickname'})}结构</Empty>
    }

    return (

      <div>
        <PageHeaderWrapper>
          <div
            style={{
              backgroundColor: '#FFFFFF',
              paddingLeft: '5%',
              paddingRight: '5%',
            }}
          />
        </PageHeaderWrapper>


          <Card>
            {/* 查询表单部分 */}
            {
              this.state.tenantTreeData && this.state.tenantTreeData.length !== 1 ?
                <TheNewForm dispatch={this.props.dispatch} showModal={this.showModal} changeFlag={this.changeFlag} tenantTreeData={this.state.tenantTreeData} setTreeMothed={this.setTreeMothed} fatherMethod={this.fatherMethod}/>
                : null
            }
            <Row gutter={16}>
              <Col span={8}>
                <Card className={style['tree-box']} >
                  {treeShow}
                </Card>
              </Col>
              <Col span={16}>
                <Card className={style['show-box']}>
                  <div className={style['show-one-block']}>
                    <p className={style.p2}>
                      当前选中：
                    </p>
                    <Input className={style['show-input']} value={this.state.selectedKeys} disabled/>
                  </div>
                  <div className={style['but-box']}>
                    <Button className={style.butt} onClick={() => this.changeFlag('brother')}>新增同级节点</Button>
                    <Button className={style.butt} onClick={() => this.changeFlag('children')}>新增子级节点</Button>
                    <Button className={style.butt} onClick={this.detailsList.bind(this)}>查看{formatMessage({ id: 'iot.organization.dept_nickname'})}信息</Button>
                  </div>
                  <div className={style['but-box']}>
                    <Button className={style.butt} onClick={() => this.changeFlag('edit')}>修改节点信息</Button>
                    <Button className={style.butt} type="danger" onClick={this.deleteList.bind(this)}>删除节点</Button>

                  </div>
                  <p className={style.p3}>
                  </p>
                </Card>
              </Col>
            </Row>
            {/* 模态框部分 */}
            <ModalBoxForm visible={this.state.visible} componentDidMount={this.componentDidMount} tenantTreeData={this.state.tenantTreeData} dispatch={this.props.dispatch} treeOne={this.state.treeOne} page_size={this.state.page_size} cancel={this.handleCancel} loading={this.state.loading} childModalChangeModalState={this.childModalChangeModalState.bind(this)} addMess={this.state.addMess} nowRow={this.state.nowRow} modalFlag={this.state.modalFlag} nowNode={this.state.nowNode} fatherProps={this.state.fatherProps} setTreeMothed={this.setTreeMothed} selectedKeys_key={this.state.selectedKeys_key} clearMothed={this.clearMothed} />
            {/* 详情模态框 */}
            <DetailsModel datailsState={this.state.datailsState} closeDatails={this.closeDatails} nowData={this.state.nowData}/>

        </Card>
      </div>
    );
  }
}

export default Organization;
//创建高阶表单组件
class NewForm extends Component {
  //表单重置
  handleReset = () => {
    this.props.form.resetFields();
  };


  //查询表单方法
  query = e => {
    const { dispatch } = this.props;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const fatherProps= {
          title: values.tenant_id.label,
          key: values.tenant_id.key,
        }
        this.props.fatherMethod(fatherProps);

        dispatch({
          type: `${namespace}/deptsTree`,
          payload: {
            tenant_id: values.tenant_id.key
          },
          callback: (res) => {
            this.props.setTreeMothed(res.data)
          }
        });
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;

    //所属租户下拉框值
    const tenantTree = this.props.tenantTreeData?this.props.tenantTreeData:[];
    if(tenantTree){
      var forTenant = [];
      for(let i=0; i<tenantTree.length; i++){
        forTenant.push(<Option value={tenantTree[i].tenant_id} key={tenantTree[i].tenant_id}>{tenantTree[i].tenant_name}</Option>)
      }
    }

    //规则就是用来打破的
    const tenant_id_rules = {
      rules: [
        {
          required: true,
          message: '必须选择一个'+formatMessage({ id: 'iot.organization.organization_search.tenant_name'})+'才能查询',
        },
      ],
    };

    return (
        /*查询表单部分*/
        <Form onSubmit={this.query.bind(this)} layout="inline">
          <div className={style['input-inline']}>
            <div className={style['input-box']}>
              <p className={style.p1} style={{ fontSize: '16px' }}>{formatMessage({ id: 'iot.organization.organization_search.tenant_name'})}：</p>
              <Form.Item>
                {getFieldDecorator('tenant_id', tenant_id_rules)(
                  <Select
                    allowClear={true}
                    showSearch
                    className={style['date-box']}
                    placeholder="请选择"
                    labelInValue
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {forTenant}
                  </Select>
                )}
              </Form.Item>
            </div>
          </div>


          <div className={style['input-inline']}>
            <Form.Item style={{ float: 'right', marginRight: 0 }}>
              <Button className={style['but-type']} htmlType="reset" onClick={this.handleReset}>
                重置
              </Button>
            </Form.Item>
            <Form.Item style={{ float: 'right', marginRight: 0 }}>
            <Button type="primary" className={style['but-type']}  htmlType="submit">
              查询
            </Button>
            </Form.Item>
        </div>
      </Form>
    );
  }
}

const TheNewForm = Form.create({ name: 'time_related_controls' })(NewForm);
